﻿using FantasticMusicPlayer.dbo.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Android.OS.Storage;
using Android.Util;

namespace FantasticMusicPlayer
{
    class CurrentDirectorySongProvider : IPlayListProvider
    {
        String savesdir = "point.conf";
        private List<PlayList> unfilteredPlaylist;

        public CurrentDirectorySongProvider(String musicRoot,String savesdir) {
            this.savesdir = savesdir;
            _musicRoot = musicRoot;
            String dir = MusicRoot;
            Log.Info("MusicInit","Scanning Dir "+dir);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
                
            }
            if (!File.Exists(Path.Combine(MusicRoot,"收藏.pl"))) { File.Create(Path.Combine(MusicRoot, "收藏.pl")).Dispose(); }
            
            EnumrateDir(dir);
            unfilteredPlaylist = _playlists;
            _playlists = unfilteredPlaylist.Where(p => p.Songs.Count > 0).ToList();
        }

        List<String> availableExtenstions = new List<string>(new string[] {".mp3",".wav",".flac",".ape",".aac" });

        public void EnumrateDir(String root) {
            if (root.Contains("/.") || root.Contains("\\."))
            {
                return;
            }
            PlayList pl = new PlayList(Path.GetFileName(root));
            PlayLists.Add(pl); 
            Directory.EnumerateFiles(root, "*.pl").OrderBy(o => o).ToList().ForEach(f => SetupVirtualList(f));
            Directory.EnumerateFiles(root).Where(o => availableExtenstions.Any(a => o.ToLower().EndsWith(a))).OrderBy(o => o).ToList().ForEach(f => pl.Songs.Add(new SongEntry(f)));
            Directory.EnumerateDirectories(root).OrderBy(o => o).ToList().ForEach(o => EnumrateDir(o));
        }

        public void UpdatePlaylist()
        {
            _playlists = unfilteredPlaylist.Where(p => p.Songs.Count > 0).ToList();
        }

        public void SetupVirtualList(String virtualList)
        {
            string name = Path.GetFileNameWithoutExtension(virtualList);
            PlayLists.Add(new VirtualDir(name, virtualList, MusicRoot));
        }

        private List<PlayList> _playlists = new List<PlayList>();
        public List<PlayList> PlayLists => _playlists;

        public PlayList LastPlayList { get; set ; }
        public SongEntry LastSong { get ; set ; }

        public void loadProgress()
        {
            int folderpos = 0;
            int songpos = 0;
            if (File.Exists(SavePath)) {
                try
                {
                    String[] content = File.ReadAllLines(SavePath);
                    folderpos = int.Parse(content[0]);
                    songpos = int.Parse(content[1]);
                }
                catch { }
            }

            LastPlayList = PlayLists[Math.Min(folderpos,PlayLists.Count-1)];
            LastSong = LastPlayList.Songs[Math.Min(songpos, LastPlayList.Songs.Count - 1)];
        }


        public String SavePath
        {

            get {
                return savesdir;
            }
        }

        private static string _musicRoot = "MP3";

        public static String MusicRoot
        {
            get
            {
                return Path.GetFullPath(Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, _musicRoot));
            }
        }
        public void saveProgress()
        {

            File.WriteAllLines(SavePath, new string[] {PlayLists.IndexOf(LastPlayList)+"",LastPlayList.Songs.IndexOf(LastSong)+"" });
        }
    }

    class VirtualDir : PlayList
    {
        private string fileName;
        private DateTime lastmodified = DateTime.MinValue;
        private string rootdir;
        private List<SongEntry> songs = new List<SongEntry>();
        public VirtualDir(string name, string file, string root) : base(name)
        {
            fileName = file;
            rootdir = root;
            checkUpdate();
        }

        void checkUpdate()
        {
            if (File.GetLastWriteTime(fileName) != lastmodified)
            {
                songs.Clear();
                songs.AddRange(File.ReadAllLines(fileName).Where(f => File.Exists(Path.Combine(rootdir, f))).Select(f => new SongEntry(Path.Combine(rootdir, f.Replace('/', Path.DirectorySeparatorChar)))));
                Console.WriteLine("Loaded playlist " + Name + " with " + songs.Count + " songs.");
                lastmodified = File.GetLastWriteTime(fileName);
            }
        }


        public void save()
        {
            File.WriteAllLines(fileName, songs.Select(s => s.getRelativePath()));
        }

        public override List<SongEntry> Songs { get { checkUpdate(); return songs; } set { } }
    }
}
